package com.jx.gocomtask.webservice.service.impl;

import com.jx.gocomtask.webservice.DTO.query.MessageQuery;
import com.jx.gocomtask.webservice.entity.ExtTaskMessage;
import com.jx.gocomtask.webservice.entity.ExtTaskMessageReply;
import com.jx.gocomtask.webservice.repository.ExtTaskMessageReplyRepository;
import com.jx.gocomtask.webservice.repository.ExtTaskMessageRepository;
import com.jx.gocomtask.webservice.service.ExtTaskMessageReplyService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import phoenics.common.exception.NotFoundException;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LWD on 2017/8/22.
 */
@Service
public class ExtTaskMessageReplyServiceImpl implements ExtTaskMessageReplyService {

    @Resource
    ExtTaskMessageRepository extTaskMessageRepository;
    @Resource
    ExtTaskMessageReplyRepository extTaskMessageReplyRepository;
    @Override
    public Page<ExtTaskMessageReply> findAll(MessageQuery query) {
        ExtTaskMessage extTaskMessage = extTaskMessageRepository.findByUuid(query.msgUUID);
        if(null == extTaskMessage)
            throw new NotFoundException();
        Specification<ExtTaskMessageReply> specification = new Specification<ExtTaskMessageReply>() {
            @Override
            public Predicate toPredicate(Root<ExtTaskMessageReply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("messageId"), extTaskMessage.getId()));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = new PageRequest(query.page, query.size, sort);
        Page<ExtTaskMessageReply> page = extTaskMessageReplyRepository.findAll(specification, pageable);
        return page;
    }

    @Override
    public ExtTaskMessageReply addReply(String msgid, String userId, ExtTaskMessageReply reply) {
        ExtTaskMessage message = extTaskMessageRepository.findByUuid(msgid);
        if(null == message)
            throw new NotFoundException();
        reply.setMessageId(message.getId());

        reply = extTaskMessageReplyRepository.save(reply);
        return reply;
    }


}
